package com.jsh.erp.controller;

import cn.hutool.core.util.StrUtil;
import com.jsh.erp.datasource.entities.Bom;
import com.jsh.erp.datasource.vo.BomCheckParam;
import com.jsh.erp.datasource.vo.BomEntity;
import com.jsh.erp.datasource.vo.BomVo4List;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.service.bom.BomService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.web.vo.BaseResponseInfo;
import com.jsh.erp.web.vo.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ji|sheng|hua jshERP
 */
@RestController
@RequestMapping(value = "/bom")
@Api(tags = {"Bom管理"})
public class BomController {

    @Resource
    private BomService bomService;

    @Deprecated
    @PostMapping("save")
    public BaseResponseInfo<Bom> save(@RequestBody Bom bom) {
        boolean isCreated = bom.getId() == null || bom.getId() == 0;
        if (isCreated && bomService.checkExist(bom.getBarCode())) {
            throw new BusinessRunTimeException("已存在该编码的Bom:" + bom.getBarCode());
        }
        bomService.save(bom);
        return BaseResponseInfo.success(bom);
    }

    /**
     * 查找bom
     *
     * @param categoryId
     * @param bomParam
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/find")
    @ApiOperation(value = "查找")
    public BaseResponseInfo<PageVO<BomVo4List>> find(@RequestParam(value = "categoryId", required = false) String categoryId,
                                                     @RequestParam(value = "bomParam", required = false) String bomParam,
                                                     @RequestParam("current") Integer currentPage,
                                                     @RequestParam("size") Integer pageSize) {
        List<BomVo4List> pageContent = bomService.findBom(bomParam, categoryId, (currentPage - 1) * pageSize, pageSize);
        Long total = bomService.countBom(bomParam, categoryId);
        PageVO<BomVo4List> pageResult = new PageVO<>();
        pageResult.setSize(pageSize);
        pageResult.setCurrent(currentPage);
        pageResult.setTotal(total);
        pageResult.setRecords(pageContent);
        return BaseResponseInfo.success(pageResult);
    }

    @DeleteMapping("delete")
    public BaseResponseInfo deleteBatch(Long id) {
        bomService.deleteByBomId(id);
        return BaseResponseInfo.success(id);
    }

    @DeleteMapping("deleteBatch")
    public BaseResponseInfo deleteBatch(String ids) {
        String[] idArray = StrUtil.splitToArray(ids, ",");
        bomService.deleteByBomIds(IdUtils.toLong(idArray));
        return BaseResponseInfo.success(idArray);
    }

    @Deprecated
    @ApiOperation("检查是否可以新增")
    @PostMapping("check")
    public BaseResponseInfo check(@RequestBody BomCheckParam bomCheckParam) {
        String barCode = bomCheckParam.getBarCode();
        boolean existForBarCode = bomService.checkExist(bomCheckParam.getBarCode());
        if (existForBarCode) {
            throw new BusinessRunTimeException("已存在该编码的Bom:" + barCode);
        }

        return BaseResponseInfo.success("ok");
    }

    @ApiOperation("保存bom信息，包括原料")
    @PostMapping("saveBom")
    public BaseResponseInfo<BomEntity> saveBom(@RequestBody BomEntity bom) {
        boolean isCreated = bom.getId() == null || bom.getId() == 0;
        if (isCreated && bomService.checkExist(bom.getBarCode())) {
            throw new BusinessRunTimeException("已存在该编码的Bom:" + bom.getBarCode());
        }

        BomEntity bomEntity = bomService.saveBom(bom, bom.getMaterials());
        return BaseResponseInfo.success(bomEntity);
    }

    @ApiOperation("获取bom实体")
    @GetMapping("getBom")
    public BaseResponseInfo<BomEntity> getBom(Long id) {
        BomEntity bomEntity = bomService.getBom(id);
        return BaseResponseInfo.success(bomEntity);
    }

    @ApiOperation("根据barCode查找Bom")
    @GetMapping("getBomByBarCode")
    public BaseResponseInfo<BomEntity> getBomByBarCode(String barCode) {
        List<Bom> boms = bomService.findByBarCode(barCode);
        boms = Optional.ofNullable(boms).orElse(Collections.EMPTY_LIST);

        if (CollectionUtils.isEmpty(boms)) {
//            throw new BusinessRunTimeException("没找到该编码对应的Bom清单" + barCode);
            return BaseResponseInfo.success(null);
        }

        Long bomId = boms.get(0).getId();
        BomEntity bomEntity = bomService.getBom(bomId);
        return BaseResponseInfo.success(bomEntity);
    }

    @ApiOperation("根据barCode查找Bom列表")
    @GetMapping("findBomByBarCodes")
    public BaseResponseInfo<List<BomEntity>> findBomByBarCodes(@RequestParam String barCodes) {
        List<String> barCodeList = StrUtil.split(barCodes, ",");
        List<Bom> boms = bomService.findByBarCodes(barCodeList);
        boms = Optional.ofNullable(boms).orElse(Collections.EMPTY_LIST);
        List<BomEntity> bomEntities = boms.stream().map(bom -> {
            return bomService.getBom(bom.getId());
        }).collect(Collectors.toList());
        return BaseResponseInfo.success(bomEntities);
    }

    /**
     * 从excel导入
     *
     * @param file
     * @return
     */
    @PostMapping("importForExcel")
    public BaseResponseInfo importForExcel(@RequestParam("file") MultipartFile file) throws IOException {
        bomService.importForExcel(file.getInputStream());
        return BaseResponseInfo.success("导入成功");
    }

}
